package com.substation.utils;

import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.interfaces.NovaCallback;

import dmax.dialog.SpotsDialog;

/**
 * Created by admin on 2018/6/13.
 */

public class LocationUtils {

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    private NovaCallback c;
    SpotsDialog spotsDialog;

    public LocationUtils(Context context,Context applicationContext, NovaCallback c) {
        this.c = c;
        spotsDialog = new SpotsDialog(context, "正在定位...");
        spotsDialog.show();
        startLocation(applicationContext);
    }

    private void startLocation(Context context) {
        //初始化定位
        mLocationClient = new AMapLocationClient(context);
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);//只获取一次定位结果
        option.setOnceLocationLatest(true);
        option.setNeedAddress(true);//设置是否返回地址信息（默认返回地址信息）

        mLocationClient.setLocationOption(option);
        //启动定位
        mLocationClient.stopLocation();
        mLocationClient.startLocation();
    }

    //异步获取定位结果
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (spotsDialog != null) {
                spotsDialog.dismiss();
                spotsDialog.cancel();
            }
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //解析定位结果
                    c.success(999, amapLocation.getLatitude() + ";" + amapLocation.getLongitude());
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    c.err(999, -1, "定位失败，错误信息：" + amapLocation.getErrorInfo());
                }
            }
            mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
            mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    };

}
